package com.qunar.wan.email;

import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.qunar.wan.common_api.model.Activity;
import com.qunar.wan.common_api.model.enums.EmailType;
import com.qunar.wan.util.VelocityUtil;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * User: tongjie.yang Date: 13-11-28 Time: 下午7:39
 */
public class EmailSender {
    public static void send(EmailType emailType, Activity activity, List<String> emails) {
        Preconditions.checkArgument(!emails.isEmpty(), "tos must not be empty!");
        createEmail(emailType, activity, emails).send();
    }

    public static void send(EmailType emailType, Activity activity, String email) {
        Preconditions.checkNotNull(email);
        List<String> emails = Lists.newArrayList();
        emails.add(email);
        createEmail(emailType, activity, emails).send();
    }

    /**
     * 创建邮件
     * 
     * @param emailType
     * @param activity
     * @param tos
     * @return
     */
    private static MailMessageFactory createEmail(EmailType emailType, Activity activity, List<String> tos) {
        MailMessageFactory mms = new MailMessageFactory();
        Map<String, Object> map = Maps.newHashMap();
        map.put("title", activity.getTitle());
        // 判断活动是否是今天开始
        SimpleDateFormat sdf0 = new SimpleDateFormat("yyyy-MM-dd");
        if (sdf0.format(activity.getStartTime()).equals(sdf0.format(new Date()))) {
            map.put("remind", "活动今天就要举行哦，记得参加");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        map.put("startTime", sdf.format(activity.getStartTime()));
        map.put("place", activity.getPlace());
        map.put("description", activity.getDescription());
        map.put("comment", activity.getCheckComment());
        map.put("actionid", activity.getId());
//        map.put("domainname", AppConfig.getItem("domainname", ""));
        // 根据邮件类型，使用vm模板获得邮件内容
        String text = VelocityUtil.getRenderResult(emailType.getVmPath(), map);
        // 获得邮件主题
        String subject = emailType.getSubject();
        // 图片路径
        StringBuilder img = new StringBuilder();
        img.append(System.getProperty("webapp.root")).append("/resources/emailimg/logo.png");
        return mms.setSubject(subject).setText(text).setImgFile("logo", img.toString()).setTo(tos);
    }
}
